package com.ilz.publictemplatedemo.utils;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.view.WindowManager;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Tools {

    // TODO: 2019/9/1 0001  toast 显示
//    public static void showToast(String text){
//        if (TextUtils.isEmpty(text))return;
//        Toast.makeText(BaseApplication.context,text,Toast.LENGTH_SHORT).show();
//    }

    public static void showToast(Context context,String text){
        if (TextUtils.isEmpty(text))return;
        Toast.makeText(context,text,Toast.LENGTH_SHORT).show();
    }

    // TODO: 2019/9/1 0001  屏幕宽高获取
    public static int getScreenWidth(Context context) {
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        if (windowManager != null) {
            windowManager.getDefaultDisplay().getMetrics(outMetrics);
        }
        return outMetrics.widthPixels;
    }

    public static int getScreenHeight(Context context) {
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        if (windowManager != null) {
            windowManager.getDefaultDisplay().getMetrics(outMetrics);
        }
        return outMetrics.heightPixels;
    }

    // TODO: 2019/9/1 0001 获取 splash    ClassName / HashKey
    public static String getClassName(Class<?> c){
        return c.getClass().getName();
    }

    public static String getHashKey(Context context) {
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                return Base64.encodeToString(md.digest(), Base64.DEFAULT);
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    // TODO: 2019/9/1 0001  检测权限
    public static boolean havePermissions(Context context, String[] pres) {
        boolean b = false;
        for (int i = 0; i < pres.length; i++) {
            b = ContextCompat.checkSelfPermission(context, pres[i]) == PackageManager.PERMISSION_GRANTED;
            if (b == false) {
                return false;
            }
        }
        return b;
    }
    public static void reqPermissions(Activity context, String[] pres) {
        ActivityCompat.requestPermissions(context,pres,100);
    }
    public static void reqPermissionsCode(Activity context, String[] pres,int requestCode) {
        ActivityCompat.requestPermissions(context,pres,requestCode);
    }


    // TODO: 2019/9/1 0001  文件存储目录
    public static String getPath(String filesName) {
        String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/"+filesName+"/";
        return dir;
    }

    public static String getSaveImagePath(Context context) {
        String resultPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString() + "/" + context.getPackageName() + "/" + "images" + "/" + System.currentTimeMillis() + ".jpg";
        return resultPath;
    }

    // TODO: 2019/9/1 0001  图片保存
    public static void saveBitmap(Bitmap bitmap, String path){
        new File(path).getParentFile().mkdirs();
        try {
            OutputStream fileOutputStream = new FileOutputStream(path);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (IOException e2) {
            e2.printStackTrace();
        }
    }

    // TODO: 2019/9/1 0001  时间格式转换
    public static String getSimpleTime(Date date){
        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
        return time;
    }

    /**
     * long转date
     */
    public Date longToDate(long dateLong){
        Date date = new Date(dateLong);
        return date;
    }

    /**
     * date转long
     */
    public long dateToLong(Date date){
        long dateLong = date.getTime();
        return  dateLong;
    }

    // TODO: 2019/9/1 获得文件Uri
    public static Uri getFileUri(Context context,String path) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return FileProvider.getUriForFile(context, context.getApplicationInfo().packageName + ".fileProvider", new File(path));
        } else {
            return Uri.fromFile(new File(path));
        }
    }

    public static String getUriToPath(Context context,Uri uri) {
        try {
            File file = new File(new URI(uri.toString()));
            return file.getAbsolutePath();
        } catch (URISyntaxException e) {
            e.printStackTrace();
            return "";
        }
    }
	
	    /**
     *
     * @param context
     * @param key 用来找到对应的值 todo SharedPreferences
     */
    public static String getSPText(Context context,String key){
        SharedPreferences preferences = context.getApplicationContext().getSharedPreferences("SP_Name", Context.MODE_PRIVATE);
        String keyValue = preferences.getString(key,"");
        return keyValue;
    }

    public static void setSPText(Context context,String key,String value){
        SharedPreferences preferences = context.getApplicationContext().getSharedPreferences("SP_Name", Context.MODE_PRIVATE);
        preferences.edit().putString(key,value).apply();
    }
}
